﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Jayden.Dll.XmlScript
{
	public interface XmlExpression
	{
		object GetValue();
	}

	public abstract class XmlBinaryExpression : List<XmlExpression>, XmlExpression
	{
		public abstract object Compute(object a, object b);

		public object GetValue()
		{
			if (Count == 0)
				return null;
			object result = this[0].GetValue();
			for (int c = 1; c < Count; c++)
				result = Compute(result, this[c].GetValue());
			return result;
		}
	}

	public class XmlObject : XmlExpression, XmlContext
	{
		private object m_Value;
		public XmlObject(object value = null) { m_Value = value; }
		public object GetValue() { return m_Value; }

		public object GetValue(string name)
		{
			if (m_Value == null)
				throw new NullReferenceException();
			Type type = m_Value.GetType();
			PropertyInfo property = type.GetProperty(name);
			return property.GetValue(m_Value, null);
		}
	}

	public class XmlAddition : XmlBinaryExpression
	{
		public override object Compute(object a, object b) { return (dynamic)a + (dynamic)b; }
	}
	public class XmlSubtraction : XmlBinaryExpression
	{
		public override object Compute(object a, object b) { return (dynamic)a - (dynamic)b; }
	}
	public class XmlMultiplication : XmlBinaryExpression
	{
		public override object Compute(object a, object b) { return (dynamic)a * (dynamic)b; }
	}
	public class XmlDivision : XmlBinaryExpression
	{
		public override object Compute(object a, object b) { return (dynamic)a / (dynamic)b; }
	}
}
